import { defineStore } from 'pinia'
import { ref } from 'vue'

interface UserInfo {
  id: number
  username: string
  avatar: string
  roles: string[]
  permissions: string[]
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')
  const isLogin = ref<boolean>(false)

  // 设置用户信息
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    isLogin.value = true
  }

  // 设置token
  const setToken = (t: string) => {
    token.value = t
    localStorage.setItem('token', t)
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = null
    token.value = ''
    isLogin.value = false
    localStorage.removeItem('token')
  }

  // 从本地存储恢复用户信息
  const restoreUserInfo = () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      token.value = savedToken
      // 这里可以根据实际需求从API获取用户信息
      // 这里仅作为示例，实际项目中应该从API获取
      userInfo.value = {
        id: 1,
        username: 'admin',
        avatar: '/avatar.png',
        roles: ['admin'],
        permissions: ['*']
      }
      isLogin.value = true
    }
  }

  return {
    userInfo,
    token,
    isLogin,
    setUserInfo,
    setToken,
    clearUserInfo,
    restoreUserInfo
  }
})